import axios from "axios"; // 引入axios
import * as aes from "@/axios/aes";
import router from "@/router/index";
import util from "@/common/util";
// @ts-ignore
import store from "../store";

let iconv = require("iconv-lite");
iconv.skipDecodeWarning = true; //忽略警告
// axios 默认配置  更多配置查看Axios中文文档
axios.defaults.timeout = 50000; // 超时默认值
axios.defaults.baseURL = "/api"; // 默认baseURL
axios.defaults.responseType = "text"; // 默认数据响应类型
axios.defaults.headers.common["Content-Type"] =
  "application/json;charset=UTF-8";
//axios.defaults.withCredentials = true;           // 表示跨域请求时是否需要使用凭证
// http request 拦截器
// 在ajax发送之前拦截 比如对所有请求统一添加header token
let loadingInstance: any = null;
axios.interceptors.request.use(
  config => {
    // 设置token
    if (store.state.token) {
      config.headers.token = store.state.token;
    }
    //数据加密
    console.log("请求数据：", config.data);
    //console.log("加密数据：", aes.Encrypt(config.data));
    config.data = aes.Encrypt(config.data);
    // loadingInstance = Loading.service({text:"请求数据",spinner:"el-icon-loading"});
    return config;
  },
  err => {
    if (loadingInstance != null) {
      loadingInstance.close();
    }
    return Promise.reject(err);
  }
);
// http response 拦截器
// ajax请求回调之前拦截 对请求返回的信息做统一处理 比如error为401无权限则跳转到登陆界面
axios.interceptors.response.use(
  response => {
    if (loadingInstance != null) {
      loadingInstance.close();
    }
    /**
     * 数据解码
     */
    //响应数据
    //console.log("响应数据加密：", response.data);
    response.data = JSON.parse(aes.Decrypt(response.data));
    console.log("响应数据解密：", response.data);
    return response;
  },
  error => {
    if (loadingInstance != null) {
      loadingInstance.close();
    }
    if (error.response.status == 401) {
      const msg = JSON.parse(aes.Decrypt(error.response.headers.errormsg));
      if (msg.state === 0) {
        if (msg.code >= 600 && msg.code <= 601) {
          util.alert(msg.msg, "提示信息", function() {
            store.state.token = "";
            router.push({ path: "/login" });
          });
        }
      }
      error.response.data = msg;
    }
    if (error.response.status == 500) {
      util.message({ state: 0, msg: "服务器错误" });
    }
    return error.response;
  }
  //
);
export default axios; // 这句千万不能漏下！！！
/**
 * post 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url: string, data = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: "post",
      url: url,
      /*headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},*/
      headers: { "Content-Type": "application/json;charset=UTF-8" },
      data: JSON.stringify(data)
    }).then(
      response => {
        resolve(response.data);
      },
      err => {
        reject(err);
      }
    );
  });
}

/**
 * get 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function get(url: string, data = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, { params: data }).then(
      response => {
        resolve(response.data);
      },
      err => {
        reject(err);
      }
    );
  });
}

/**
 *  删除
 * @param url
 * @param data
 */
export function del(url: string, data = {}) {
  return new Promise((resolve, reject) => {
    axios({
      method: "delete",
      url: url,
      /*headers:{"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"},*/
      headers: { "Content-Type": "application/json;charset=UTF-8" },
      data: JSON.stringify(data)
    }).then(
      response => {
        resolve(response.data);
      },
      err => {
        reject(err);
      }
    );
  });
}

/**
 * 可以查看中文文档 自行封装
 */
export function requestAssign(url: string, data = {}, method: any) {
  return new Promise((resolve, reject) => {
    if (method.toLowerCase() === "get".toLowerCase()) {
      resolve(get(url, data));
    } else if (method.toLowerCase() === "post".toLowerCase()) {
      resolve(post(url, data));
    }
  });
}
